import requests
import sys

from plugins.plugin import Plugin

sys.path.append("..")
from src.video import Video
from src.playlist import Playlist
from src.history import History
from src.config import Config

class AnilibriaRandom(Plugin):

    def __init__(self, history: History=History(), config: Config=Config()) -> None:
        super().__init__(history, config)

        self.history = history
        self.config = config

        self.name = "[+] AnilibriaTV: Random anime"
        self.category = "AnilibriaTV"

        self.query_description = """"""
        
        self.params = {
            'api_instance' : False
        }

        self.flag = "-alr"
        self.full_flag = "--anilibriarandom"
        self.flag_help = "show random anime"
        self.flag_action = "store_true"
        
        self.save_config()

        self.api_instance = self.config.get_option(self.category, 'api-instance')
        self.instance = self.config.get_option(self.category, 'instance')

    def get_random(self, params):
        api_instance = self.api_instance
        if 'api_instance' in params:
            api_instance = params['api_instance']
        resp = requests.get(f"{api_instance}/getRandomTitle")

        if resp.status_code != 200: return list()
        resp = resp.json()

        items = []
        title = f"{resp['names']['ru']} ({resp['names']['en']})"
        host = "https://" + resp["player"]["host"]
        purl = f"{self.instance}/release/{resp['code']}.html"
        videos = list()

        for vid in resp["player"]["playlist"].values():
            ititle = "Episode " + str(vid["serie"])
            video = Video()
            video.title=ititle
            video.videoId = vid["hls"]["hd"]
            video.url=host+vid["hls"]["hd"]
            video.length=resp["type"]["length"]
            
            video.isWatched = video.in_history(self.history)

            videos.append(video.to_json())

        playlist = Playlist(title, videos, url=purl)

        items.append(playlist.to_json())

        return items

    def get_items(self, params):
        return self.get_random(params)

    def save_config(self):
        self.config.set_option(self.category, 'api-instance', 'https://api.anilibria.tv/v2')
        self.config.set_option(self.category, 'instance', 'https://anilibria.tv')


